import datetime
from flask import Flask, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS

app = Flask(__name__)
# CORS(app)
CORS(app, resources={r"/*": {'origins': "*"}})
CORS(app, resources={r"/*": {'origins': 'http://localhost:8080/', "allow_headers": "Access-Control-Request-Headers"}})

# 配置与预处理
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 中文乱码问题
app.config['JSON_AS_ASCII'] = False

db = SQLAlchemy(app)
ma = Marshmallow(app)


# 数据库处理类


class Articles(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    body = db.Column(db.Text())
    date = db.Column(db.DateTime, default=datetime.datetime.now)

    def __init__(self, title, body):
        self.title = title
        self.body = body

    def __str__(self):
        return self.title


# 创建格式化工具类


class ArticlesSchema(ma.Schema):
    class Meta:
        fields = ('id', 'title', 'body', 'date')
        ordered = True  # 转换成有序字典


# 格式化工具类实例化
article_schema = ArticlesSchema()
articles_schema = ArticlesSchema(many=True)


# 路由与逻辑处理
# =============================

@app.route('/get', methods=['GET'])  # 获取所有文章
def get_articles():
    all_articles = Articles.query.all()
    results = articles_schema.dump(all_articles)  # 使用schema格式化数据
    return jsonify(results)


@app.route('/get/<id>/', methods=['GET', 'OPTIONS'])  # 获取所有文章
def post_details(id):
    headers = {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
    }
    if request.method == 'OPTIONS':
        print("使用OPTIONS方法")
        article = Articles.query.get(id)
        return make_response((article_schema.jsonify(article)), 202, headers)
    if request.method == 'GET':
        print("使用GET方法")
        article = Articles.query.get(id)
        return article_schema.jsonify(article)


@app.route('/add', methods=['POST'])  # 添加文章
def add_article():
    title = request.json['title']
    body = request.json['body']
    articles = Articles(title, body)
    db.session.add(articles)
    db.session.commit()
    return article_schema.jsonify(articles)


@app.route('/del/<id>/', methods=['DELETE'])  # 删除文章
def article_delete(id):
    article = Articles.query.get(id)
    db.session.delete(article)
    db.session.commit()
    return article_schema.jsonify(article)

    # return article_schema.jsonify(article)


if __name__ == "__main__":
    app.run(debug=True)
